<template>
  <div>
    <BreadCrumb pathOne="内容管理" pathTwo="公益中心管理"></BreadCrumb>
    <div>
      <el-form :inline="true">
        <el-form-item label="文章名" size="large">
          <el-input
            clearable
            size="large"
            v-model="searchName"
            style="width: 240px"
            placeholder="请输入文章名"
          />
        </el-form-item>

        <el-form-item label="选择作者" size="large">
          <el-select
            @clear="articleClassifyId = ''"
            clearable
            v-model="articleClassifyId"
            placeholder="无"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in AllClassify"
              :key="item.id"
              :value="item.id"
              :label="item.counselorName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query" size="large">搜索</el-button>
          <el-button type="primary" @click="createOrUpdate('')" size="large">新增</el-button>
          <el-button type="danger" size="large" @click="batchDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%; margin-top: 10px"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" />
        <el-table-column fixed prop="id" label="id" />
        <el-table-column prop="title" label="文章名" show-overflow-tooltip />
        <el-table-column prop="description" label="文章简介" show-overflow-tooltip />
        <el-table-column prop="counselor.name" label="咨询师名" />
        <el-table-column label="缩略图">
          <template #default="scope">
            <!-- <img :src="scope.row.listView" alt="缩略图"> -->
            <el-avatar
              shape="square"
              size="large"
              :src="'http://localhost:8080' + scope.row.listView"
            />
          </template>
        </el-table-column>
        <el-table-column prop="time" label="创建时间" />
        <el-table-column label="状态">
          <!-- 0是审核中，1是通过，2是不通过 -->
          <el-tag type="success">正常</el-tag>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="260">
          <template #default="scope">
            <el-button size="small" type="primary" @click="createOrUpdate(scope.row.id)"
              >编辑</el-button
            >
            <el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
            <el-button size="small" type="primary" @click="searchArticleDetails(scope.row.id)"
              >查看详情内容</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      v-model="dialogFormVisible"
      :title="form.id == '' ? '新增' : '编辑'"
      width="700"
      style="margin-bottom: 60px"
      @close="clearFormValue"
    >
      <!-- <el-form :model="form"> -->
      <el-form>
        <el-form-item label="文章标题" label-width="auto" label-position="top">
          <el-input
            size="large"
            v-model="form.title"
            autocomplete="off"
            placeholder="请输入文章标题"
          />
        </el-form-item>
        <el-form-item label="文章简介" label-width="auto" label-position="top">
          <el-input
            size="large"
            v-model="form.description"
            autocomplete="off"
            placeholder="请输入文章简介"
          />
        </el-form-item>
        <el-form-item label="咨询师作者" size="large" label-position="top">
          <el-select v-model="form.psycCounselorId" placeholder="无" size="large">
            <el-option
              v-for="item in AllClassify"
              :key="item.id"
              :value="item.id"
              :label="item.counselorName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缩略图" label-position="top">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.listView"
              :src="'http://localhost:8080' + form.listView"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容详情" label-width="auto" label-position="top">
          <QuillEditor :value="form.detaile" @updateValue="getMsg"></QuillEditor>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="((dialogFormVisible = false), add())"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogArticleDetails"
      title="内容详情"
      width="700"
      style="margin-bottom: 60px"
      @close="clearFormValue"
    >
      <el-form-item label="" label-width="auto" label-position="top">
        <QuillEditor :value="form.detaile" @updateValue="getMsg"></QuillEditor>
      </el-form-item>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import BreadCrumb from '../../components/BreadCrumb.vue'
import QuillEditor from '../../components/QuillEditor.vue'
const axios = getCurrentInstance().appContext.config.globalProperties.axios
/*
头部表单所需要的数据
*/
const searchName = ref('')
const articleClassifyId = ref('')
const AllClassify = ref([])
const getAllClassify = () => {
  axios.get(`counselor/page?id=&pageNum=&pageSize=`).then((resp) => {
    console.log('全部分类：', resp)
    AllClassify.value = resp.data.list
  })
}
const query = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }
  if (searchName.value !== '') {
    // 判断不为空字符串
    params.title = searchName.value
  }
  if (articleClassifyId.value !== '') {
    // 判断不为空字符串
    params.psycCounselorId = articleClassifyId.value
  }
  axios
    .get('http://localhost:8080/psyc/page', {
      params: params,
    })
    .then((resp) => {
      console.log('数据查询响应：', resp)
      tableData.value = resp.data.pageInfo.list
      total.value = resp.data.pageInfo.total
      console.log('表格数据：', tableData.value)
    })
}
const ids = ref('')
const batchDelete = () => {
  if (!ids.value) {
    ElMessage.info('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete('http://localhost:8080/psyc/batch', {
          params: {
            ids: ids.value,
          },
        })
        .then((res) => {
          ElMessage.success('删除成功')
          query()
        })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
    .finally(() => {
      query()
    })
}
/*
el-table所需要的数据
*/
const tableData = ref([])
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id).join(',')
  console.log('批量删除的ids为:', ids.value)
}
const createOrUpdate = (id) => {
  console.log('id为', id)
  dialogFormVisible.value = true
  if (id == '') {
    clearFormValue()
  } else {
    axios
      .get('http://localhost:8080/psyc', {
        params: {
          id: id,
        },
      })
      .then((resp) => {
        console.log('编辑查询的响应', resp)
        form.value = resp.data
        console.log('最新表单数据', form.value)
      })
  }
}
const remove = (id) => {
  console.log('当前行的数据', id)
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete('http://localhost:8080/psyc', {
          params: {
            id: id,
          },
        })
        .then((resp) => {
          console.log('删除后：', resp)
          if (resp.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage.error('删除失败')
          }
        })
        .finally(() => {
          query()
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const searchArticleDetails = (id) => {
  dialogArticleDetails.value = true
  if (id == '') {
    clearFormValue()
  } else {
    axios
      .get('http://localhost:8080/psyc', {
        params: {
          id: id,
        },
      })
      .then((resp) => {
        form.value = resp.data
        console.log('编辑查询：', resp)
      })
  }
}
/*
分页组件所需要的数据
*/
const currentPage = ref(1) // 当前页
const pageSize = ref(10) // 每页显示条目数
const size = 'default' // 分页大小
const total = ref(0)
const handleSizeChange = (val) => {
  pageSize.value = val
  query()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}
/*
弹出框所需要的数据
*/
const dialogFormVisible = ref(false)
// const articleClassifyName = ref('')
const form = ref({
  addOrUpdateFlag: 1,
  counselorId: '',
  time: '',
  del: 0,
  detaile: ' ',
  id: '',
  description: '',
  listView: '',
  title: '',
})
const getMsg = (val) => {
  form.value.detaile = val
}
const clearFormValue = () => {
  form.value = {
    addOrUpdateFlag: 1,
    counselorId: '',
    time: '',
    del: 0,
    detaile: ' ',
    id: '',
    description: '',
    listView: '',
    title: '',
  }
}
const add = () => {
  console.log('点击新增保存后传入的：', form.value)
  if (form.value.id == '') {
    form.value.time = getCurrentFormattedDateTime()
    axios
      .post(
        'http://localhost:8080/psyc/add-selective',

        form.value,
      )
      .then((resp) => {
        if (resp.code == 200) {
          ElMessage({
            message: '新增成功',
            type: 'success',
          })
        } else {
          ElMessage.error('新增失败')
        }
      })
      .finally(() => {
        query()
      })
  } else {
    form.value.time = getCurrentFormattedDateTime()
    axios
      .put('http://localhost:8080/psyc', form.value)
      .then((resp) => {
        if (resp.code == 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
        } else {
          ElMessage.error('修改失败')
        }
      })
      .finally(() => {
        query()
      })
  }
}
function handleAvatarSuccess(resp) {
  console.log('文件上传成功', resp)
  form.value.listView = resp.data
}
/*
内容详情对话框
*/
const dialogArticleDetails = ref(false)
function getCurrentFormattedDateTime() {
  const now = new Date() // 获取当前的 Date 对象

  // 提取日期部分
  const year = now.getFullYear()
  // getMonth() 返回 0-11，所以需要 +1
  // padStart(2, '0') 确保是两位数，不足补零
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')

  // 提取时间部分
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  const seconds = now.getSeconds().toString().padStart(2, '0')

  // 拼接成目标格式的字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
onMounted(() => {
  query()
  getAllClassify()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
